import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class XrCache {
  late SharedPreferences _prefs;

  XrCache._() {
    init();
  }

  static XrCache? _instance;

  XrCache._pre(SharedPreferences prefs) {
    this._prefs = prefs;
  }

  ///预初始化，防止在使用get时，prefs还未完成初始化
  static Future<XrCache> preInit() async {
    if (_instance == null) {
      var prefs = await SharedPreferences.getInstance();
      _instance = XrCache._pre(prefs);
    }
    return _instance!;
  }

  static XrCache getInstance() {
    if (_instance == null) {
      _instance = XrCache._();
    }
    return _instance!;
  }

  init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  setString(String key, String value) {
    return _prefs.setString(key, value);
  }

  setDouble(String key, double value) {
    return _prefs.setDouble(key, value);
  }

  setInt(String key, int value) {
    return _prefs.setInt(key, value);
  }

  setBool(String key, bool value) {
    return _prefs.setBool(key, value);
  }

  getBool(String key) {
    return _prefs.getBool(key);
  }

  getString(String key) {
    return _prefs.getString(key);
  }

  setStringList(String key, List<String> value) {
    return _prefs.setStringList(key, value);
  }

  List<String>? getStringList(String key) {
    return _prefs.getStringList(key);
  }

  ///存储对象
  Future<bool> setObject(String key, Object value) {
    return _prefs.setString(key, json.encode(value));
  }

  /// 获取对象
  T? getObject<T>(String key, T f(Map v), {T? defValue}) {
    String? data = _prefs.get(key) as String?;
    if (data == null) {
      return null;
    }
    Map? map = json.decode(data);
    return map == null ? defValue : f(map);
  }

  remove(String key) {
    return _prefs.remove(key);
  }

  T? get<T>(String key) {
    var result = _prefs.get(key);
    if (result != null) {
      return result as T;
    }
    return json.decode(result.toString());
  }
}
